import { createBrowserRouter, redirect } from 'react-router'
import { healthApi } from './api/health/health'

const authLoader = async () => {
  const res = await healthApi()
  if (res.code == 401) {
    return redirect('/login')
  } else {
    localStorage.setItem('user', JSON.stringify(res.data))
  }
  return res.data
}

const router = createBrowserRouter([
  {
    path: '/welcome',
    lazy: async () => ({
      Component: (await import('./pages/Welcome')).default,
    }),
    loader: () => authLoader(),
  },
  {
    path: '/login',
    lazy: async () => ({ Component: (await import('./pages/Login')).default }),
  },
  {
    path: '*',
    loader: () => redirect('/welcome'),
  },
])

export default router
